<template>
  <div class="contract-list-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入合同编号/企业名称/客户名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 270px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
         <el-select
          v-model="statusFilter"
          placeholder="请选择合同状态"
          size="small"
          style="width: 150px; margin-left: 10px;"
          clearable
        >
          <el-option label="全部状态" :value="''"></el-option>
          <el-option label="未付款" :value="0">
            <el-tag type="warning" size="mini">未付款</el-tag>
          </el-option>
          <el-option label="已付款" :value="1">
            <el-tag type="success" size="mini">已付款</el-tag>
          </el-option>
        </el-select>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 合同列表表格 -->
    <el-table 
      :data="contractList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="contract_name" label="合同编号" min-width="200px"></el-table-column>
      <el-table-column prop="companyName" label="企业名称" min-width="200px"></el-table-column>
      <el-table-column prop="customer_name" label="客户名称" width="150px"></el-table-column>
      <el-table-column prop="customer_phone" label="手机号" width="130px"></el-table-column>
      <el-table-column prop="cost" label="合同金额" width="120px" align="center">
        <template slot-scope="scope">
          ¥{{ formatMoney(scope.row.cost) }}
        </template>
      </el-table-column>
      <el-table-column prop="payment_status" label="付款状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.payment_status === 1 ? 'success' : 'warning'">
            {{ scope.row.payment_status === 1 ? '已付款' : '未付款' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="payment_time" label="付款时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.payment_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="estimated_payment_time" label="预计付款时间" width="160px" align="center">
        <template slot-scope="scope">
            {{ formatDateTime(scope.row.estimated_payment_time) }}
          <span style="color: #999;">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="is_construction" label="施工状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_construction === 1 ? 'success' : 'info'">
            {{ scope.row.is_construction === 1 ? '施工' : '不施工' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="合同备注" max-width="150px" show-overflow-tooltip></el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="update_time" label="更新时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.update_time) }}
        </template>
      </el-table-column> -->
       <el-table-column label="合同凭证" width="100px" align="center">
         <template slot-scope="scope">
           <el-button 
             v-if="scope.row.img_url" 
             type="text" 
             size="small" 
             @click="handleViewImage(scope.row.img_url)"
           >
             查看凭证
           </el-button>
           <span v-else style="color: #999;">无凭证</span>
         </template>
       </el-table-column>
       <el-table-column label="付款凭证" width="100px" align="center">
         <template slot-scope="scope">
           <el-button 
             v-if="scope.row.evidence_payment" 
             type="text" 
             size="small" 
             @click="handleViewPaymentImage(scope.row.evidence_payment)"
           >
             查看凭证
           </el-button>
           <span v-else style="color: #999;">无凭证</span>
         </template>
       </el-table-column>
       <el-table-column label="操作" width="220px" align="center" fixed="right">
         <template slot-scope="scope">
           <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
           <el-button type="text" size="small" @click="handleGenerateOrder(scope.row)" style="margin-left: 10px;">生成订单</el-button>
           <el-button type="text" size="small" @click="handleViewOrders(scope.row)" style="margin-left: 10px;">查看订单</el-button>
           <el-button type="text" size="small" @click="handleDeleteContract(scope.row)">删除</el-button>  
          </template>
       </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 合同凭证图片预览弹窗 -->
    <el-dialog
      title="合同凭证"
      :visible.sync="imageDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      center
    >
      <div class="image-preview-container">
        <el-image 
          v-for="(url, idx) in currentImageUrls"
          :key="url"
          :src="url"
          style="width: 100%; max-height: 500px; margin-bottom: 10px;"
          fit="contain"
          :preview-src-list="currentImageUrls"
          :initial-index="idx"
          lazy
        >
          <div slot="placeholder" class="image-slot">
            <i class="el-icon-loading"></i>
            <p>图片加载中...</p>
          </div>
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            <p>图片加载失败</p>
            <!-- <p style="font-size: 12px; margin-top: 5px;">{{ currentImageUrl }}</p> -->
          </div>
        </el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imageDialogVisible = false">关 闭</el-button>
        <!-- <el-button type="primary" @click="openImageInNewTab">在新窗口打开</el-button> -->
      </div>
    </el-dialog>

    <!-- 付款凭证图片预览弹窗 -->
    <el-dialog
      title="付款凭证"
      :visible.sync="paymentImageDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      center
    >
      <div class="image-preview-container">
        <el-image 
          v-for="(url, idx) in currentPaymentImageUrls"
          :key="url"
          :src="url"
          style="width: 100%; max-height: 500px; margin-bottom: 10px;"
          fit="contain"
          :preview-src-list="currentPaymentImageUrls"
          :initial-index="idx"
          lazy
        >
          <div slot="placeholder" class="image-slot">
            <i class="el-icon-loading"></i>
            <p>图片加载中...</p>
          </div>
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            <p>图片加载失败</p>
          </div>
        </el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="paymentImageDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 生成订单产品选择弹窗 -->
    <el-dialog
      title="选择产品生成订单"
      :visible.sync="orderDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      center
    >
      <div class="product-selection-container">
        <div class="contract-info">
          <h4>合同信息</h4>
          <p><strong>合同名称：</strong>{{ currentContract.contract_name }}</p>
          <p><strong>客户名称：</strong>{{ currentContract.companyName }}</p>
        </div>
        
        <div class="product-list">
          <h4>设备列表</h4>
          
          <!-- 产品搜索框 -->
          <div class="product-search">
            <el-input
              v-model="productSearchKeyword"
              placeholder="请输入产品名称进行搜索"
              prefix-icon="el-icon-search"
              size="small"
              style="width: 300px;"
              clearable
              @input="filterProducts"
            ></el-input>
          </div>
          
          <div v-for="device in filteredDeviceList" :key="device.id" class="device-item">
            <div class="device-header">
              <div class="device-title">
                <strong>{{ device.device_name }}</strong>
                <el-tag v-if="device.is_need" type="warning" size="mini">需要流量卡</el-tag>
                <el-tag v-else type="info" size="mini">无需流量卡</el-tag>
              </div>
              <div class="device-actions">
                <div class="quantity-selector">
                  <label>数量：</label>
                  <el-input-number 
                    v-model="device.quantity" 
                    :min="1" 
                    :max="9999"
                    size="mini"
                    style="width: 100px;"
                    placeholder="数量"
                    @change="handleDeviceQuantityChange(device)"
                  ></el-input-number>
                </div>
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="addDeviceToCart(device)"
                  icon="el-icon-plus"
                >
                  添加产品
                </el-button>
              </div>
            </div>
            
            <div class="factory-info">
              <span><strong>工厂：</strong>{{ device.factory.factory_name }}</span>
              <span><strong>地址：</strong>{{ device.factory.address }}</span>
            </div>
            
            <!-- 配件列表 -->
            <div class="accessories-list">
              <h5>配件列表：</h5>
              <div class="accessories-grid">
                <div 
                  v-for="accessory in device.accessories" 
                  :key="accessory.id"
                  class="accessory-item"
                >
                  <div class="accessory-header">
                    <el-checkbox 
                      v-model="accessory.selected" 
                      @change="handleAccessoryChange(device, accessory)"
                    >
                      <span class="accessory-name">{{ accessory.accessory_name }}</span>
                    </el-checkbox>
                    <el-tag 
                      :type="accessory.is_standard === 1 ? 'success' : 'warning'" 
                      size="mini"
                    >
                      {{ accessory.is_standard === 1 ? '标配' : '选配' }}
                    </el-tag>
                  </div>
                  
                  <!-- 规格选择 -->
                  <div v-if="accessory.selected && accessory.skus && accessory.skus.length > 0" class="sku-selection">
                    <div class="form-item">
                      <label class="form-label">规格：</label>
                      <el-select 
                        v-model="accessory.selectedSkuId" 
                        placeholder="请选择规格"
                        size="small"
                        style="width: 200px;"
                      >
                        <el-option 
                          v-for="sku in accessory.skus" 
                          :key="sku.id"
                          :label="sku.value" 
                          :value="sku.id"
                        ></el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 已选产品列表 -->
        <div class="selected-products">
          <h4>已选产品 
            <el-button type="text" size="mini" @click="clearCart" style="margin-left: 10px;">清空已选择产品</el-button>
            <el-button 
              v-if="cartItems.length > 0" 
              type="text" 
              size="mini" 
              @click="syncShippingInfo" 
              style="margin-left: 10px; color: #409eff;"
              icon="el-icon-refresh"
            >
              同步发货信息
            </el-button>
          </h4>
          <div v-if="cartItems.length === 0" class="empty-cart">
            <p style="color: #999; text-align: center; padding: 20px;">未选则任何产品，请选择产品</p>
          </div>
          <div v-else class="cart-items">
            <div v-for="(item, index) in cartItems" :key="index" class="cart-item">
                             <div class="cart-item-header">
                 <div class="device-info">
                   <span class="device-name">{{ item.device_name }}</span>
                                       <span v-if="item.accessories && item.accessories.length > 0" class="device-config">
                      ({{ item.accessories.map(acc => {
                        if (acc.sku_value && acc.sku_value.trim()) {
                          return acc.accessory_name + ' - ' + acc.sku_value;
                        } else {
                          return acc.accessory_name;
                        }
                      }).join(', ') }})
                    </span>
                 </div>
                 <el-button 
                   type="danger" 
                   size="mini" 
                   @click="removeFromCart(index)"
                   icon="el-icon-delete"
                 >
                   删除
                 </el-button>
               </div>
              
              <div class="cart-item-details">
                <div class="quantity-section">
                  <label>数量：</label>
                  <el-input-number 
                    v-model="item.quantity" 
                    :min="1" 
                    :max="9999"
                    size="mini"
                    style="width: 100px;"
                  ></el-input-number>
                </div>
                
                <div class="accessories-section" v-if="item.accessories && item.accessories.length > 0">
                  <label>配件：</label>
                  <div class="accessories-tags">
                    <el-tag 
                      v-for="accessory in item.accessories" 
                      :key="accessory.id"
                      size="mini"
                      :type="accessory.is_standard === 1 ? 'success' : 'warning'"
                    >
                      {{ accessory.accessory_name }}{{ accessory.sku_value ? ' - ' + accessory.sku_value : '' }}
                      <span style="font-size: 10px; margin-left: 4px;">({{ accessory.is_standard === 1 ? '标配' : '选配' }})</span>
                    </el-tag>
                  </div>
                </div>
                
                <!-- 发货信息区域 -->
                <div class="shipping-info-section">
                  <h5 class="shipping-title">
                    <i class="el-icon-location"></i>
                    发货信息
                  </h5>
                  <div class="shipping-form">
                    <el-row :gutter="15">
                      <el-col :span="8">
                        <div class="form-item">
                          <label class="form-label">收货人：</label>
                          <el-input 
                            v-model="item.shipping_info.recipient_name" 
                            placeholder="收货人姓名"
                            size="small"
                            clearable
                          ></el-input>
                        </div>
                      </el-col>
                      <el-col :span="8">
                        <div class="form-item">
                          <label class="form-label">联系电话：</label>
                          <el-input 
                            v-model="item.shipping_info.recipient_tel" 
                            placeholder="联系电话"
                            size="small"
                            clearable
                          ></el-input>
                        </div>
                      </el-col>
                      <el-col :span="8">
                        <div class="form-item">
                          <label class="form-label">收货地址：</label>
                          <el-input 
                            v-model="item.shipping_info.recipient_address" 
                            placeholder="收货地址"
                            size="small"
                            clearable
                          ></el-input>
                        </div>
                      </el-col>
                    </el-row>
                    <el-row :gutter="15" style="margin-top: 10px;">
                      <el-col :span="24">
                        <div class="form-item">
                          <label class="form-label">订单备注：</label>
                          <el-input 
                            v-model="item.shipping_info.remark" 
                            placeholder="请输入该产品的订单备注信息"
                            type="textarea"
                            :rows="2"
                            size="small"
                            clearable
                          ></el-input>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOrderGeneration" :loading="orderLoading">生成订单</el-button>
      </div>
    </el-dialog>

    <!-- 查看订单弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="ordersDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      center
    >
      <div class="orders-container">
        <div class="contract-info">
          <h4>合同信息</h4>
          <p><strong>合同编号：</strong>{{ currentContractForOrders.contract_name }}</p>
          <p><strong>公司名称：</strong>{{ currentContractForOrders.companyName }}</p>
        </div>
        
        <div class="orders-list" v-loading="ordersLoading">
          <h4>订单列表</h4>
          <el-table :data="ordersList" style="width: 100%" border>
            <!-- <el-table-column label="订单ID" prop="id" width="80" align="center"></el-table-column> -->
            <el-table-column label="设备信息" width="150" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.devices.device_name }}</div>
                <!-- <div style="font-size: 12px; color: #999;">ID: {{ scope.row.devices.id }}</div> -->
              </template>
            </el-table-column>
            <el-table-column label="工厂信息" width="200" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.factory.factory_name }}</div>
                <div style="font-size: 12px; color: #999;">{{ scope.row.factory.address }}</div>
              </template>
            </el-table-column>
            <el-table-column label="配件信息" min-width="200">
              <template slot-scope="scope">
                <div v-if="scope.row.accessory_skus && scope.row.accessory_skus.length > 0">
                  <el-tag 
                    v-for="accessory in scope.row.accessory_skus" 
                    :key="accessory.accessory_id"
                    size="mini"
                    style="margin: 2px;"
                  >
                    {{ accessory.accessory_name }}{{ accessory.sku_value ? ' - ' + accessory.sku_value : '' }}
                  </el-tag>
                </div>
                <div v-else style="color: #999; font-size: 12px;">无配件</div>
              </template>
            </el-table-column>
            <el-table-column label="设备数量" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.device_quantity || 1 }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
              <template slot-scope="scope">
                <el-tag 
                  :type="getStatusType(scope.row.status)" 
                  size="mini"
                >
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="物流单号" width="150" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.track_number">{{ scope.row.track_number }}</span>
                <span v-else style="color: #999;">暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="160" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column label="备注" width="150" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
                <span v-else style="color: #999;">暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button 
                  type="text" size="small"
                  @click="handleDeleteOrder(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="ordersDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getContractList, getProductList, getDeviceListMore, generateOrder, getOrdersByContractId, deleteOrder,deleteContract } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';
import { baseURLs } from '@/utils/request';

export default {
  name: 'ContractManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      //状态筛选字段
      statusFilter:'',

      // 列表相关
      contractList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 图片预览弹窗相关
      imageDialogVisible: false,
      currentImageUrls: [], // 支持多张图片
      paymentImageDialogVisible: false,
      currentPaymentImageUrls: [], // 付款凭证图片
      
      // 生成订单弹窗相关
      orderDialogVisible: false,
      orderLoading: false,
      currentContract: {},
      deviceList: [],
      cartItems: [], 
      
      // 查看订单弹窗相关
      ordersDialogVisible: false,
      ordersLoading: false,
      currentContractForOrders: {},
      ordersList: [],

      // 产品搜索相关
      productSearchKeyword: '',
      filteredDeviceList: []
    }
  },
  mounted() {
    this.fetchContractList();
  },
  methods: {
  async handleDeleteContract(contract) {
      try {
        await this.$confirm(`确定要删除该合同吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await deleteContract(contract.id);
        
        if (response.data && response.data.code) {
          this.$message.success('删除合同成功');
          // 重新加载订单列表
          this.fetchContractList();
        } else {
          this.$message.error(response.data.msg || '删除合同失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除合同失败:', error);
          this.$message.error('删除合同失败');
        }
      }
    },
    // 获取合同列表
    async fetchContractList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        };

        // 只有当statusFilter有有效值时才添加该参数
        if (this.statusFilter || this.statusFilter === 0) {
          params.payment_status = this.statusFilter;
        }
        
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword;
        }
        
        const response = await getContractList(params);
        
        if (response.data && response.data.code) {
          // API成功返回数据
          this.contractList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取合同列表失败');
        }
      } catch (error) {
        console.error('获取合同列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取合同列表失败');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchContractList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.statusFilter='';
      this.fetchContractList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchContractList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchContractList();
    },
    
    // 查看合同凭证图片（支持多张图片，分号分隔）
    handleViewImage(imageUrl) {
      if (imageUrl) {
        this.currentImageUrls = imageUrl.split(',').filter(Boolean);
      } else {
        this.currentImageUrls = [];
      }
      this.imageDialogVisible = true;
    },
    
    // 查看付款凭证图片（支持多张图片，分号分隔）
    handleViewPaymentImage(imageUrl) {
      if (imageUrl) {
        this.currentPaymentImageUrls = imageUrl.split(',').filter(Boolean);
      } else {
        this.currentPaymentImageUrls = [];
      }
      this.paymentImageDialogVisible = true;
    },
    
    // 在新窗口打开所有图片
    openImageInNewTab() {
      if (this.currentImageUrls && this.currentImageUrls.length) {
        this.currentImageUrls.forEach(url => {
          window.open(url, '_blank');
        });
      }
    },
    
    // 修改合同
    handleEdit(row) {
      // 跳转到合同编辑页面，传递合同数据
      this.$router.push({
        name: 'ContractEdit',
        params: {
          id: row.id,
          contractData: row
        }
      });
    },
    
    // 生成订单
    handleGenerateOrder(row) {
      this.currentContract = row;
      this.orderDialogVisible = true;
      this.clearCart(); 
      this.loadDeviceList();
      
      // 自动填充收货人信息到所有已选产品
      this.$nextTick(() => {
        // 延迟执行，确保弹窗已打开
        setTimeout(() => {
          this.autoFillShippingInfo();
        }, 100);
      });
    },
    
    // 自动填充发货信息
    autoFillShippingInfo() {
      if (this.currentContract) {
        // 从合同数据中获取收货人信息
        const recipientInfo = {
          recipient_name: this.currentContract.recipient_name || '',
          recipient_tel: this.currentContract.recipient_tel || '',
          recipient_address: this.currentContract.recipient_address || '',
          remark: ''
        };
        
        // 更新所有已选产品的发货信息
        this.cartItems.forEach(item => {
          item.shipping_info = { ...recipientInfo };
        });
      }
    },
    
    // 加载设备列表
    async loadDeviceList() {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await getDeviceListMore();
        
        if (response.data && response.data.code === true) {
          // 处理设备数据，为配件添加选择状态和默认规格选择
          this.deviceList = response.data.data.map(device => ({
            ...device,
            quantity: 1, // 默认数量为1
            accessories: device.accessories.map(accessory => {
              const accessoryData = {
                ...accessory,
                selected: accessory.is_standard === 1, // 标配默认选中，选配默认不选中
                selectedSkuId: null // 初始化为null
              };
              
              // 如果有规格，设置默认选择第一个
              if (accessory.skus && accessory.skus.length > 0) {
                accessoryData.selectedSkuId = accessory.skus[0].id;
              }
              
              return accessoryData;
            })
          }));
          
          // 初始化过滤后的列表
          this.filteredDeviceList = [...this.deviceList];
          
          // 调试信息
          console.log('设备列表数据:', this.deviceList);
        } else {
          this.$message.error(response.data.msg || '获取设备列表失败');
        }
      } catch (error) {
        console.error('获取设备列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取设备列表失败');
        }
      }
    },

    // 过滤产品列表
    filterProducts() {
      this.filteredDeviceList = this.deviceList.filter(device => 
        device.device_name.toLowerCase().includes(this.productSearchKeyword.toLowerCase())
      );
    },
    
    // 添加设备
    addDeviceToCart(device) {
      // 收集选中的配件（标配和手动选中的选配）
      const selectedAccessories = [];
      device.accessories.forEach(accessory => {
        if (accessory.selected) {
          const accessoryItem = {
            id: accessory.id,
            accessory_name: accessory.accessory_name,
            is_standard: accessory.is_standard,
            sku_id: accessory.selectedSkuId,
            sku_value: accessory.selectedSkuId ? accessory.skus.find(sku => sku.id === accessory.selectedSkuId)?.value : null
          };
          selectedAccessories.push(accessoryItem);
        }
      });
      
      // 生成唯一的项目标识（设备ID + 配件组合的哈希值）
      const accessoriesHash = this.generateAccessoriesHash(selectedAccessories);
      const cartItemKey = `${device.id}_${accessoriesHash}`;
      
      // 检查是否已存在相同配置的设备
      const existingCartItem = this.cartItems.find(item => {
        const itemAccessoriesHash = this.generateAccessoriesHash(item.accessories);
        return item.device_id === device.id && itemAccessoriesHash === accessoriesHash;
      });
      
      if (existingCartItem) {
        // 如果配置已存在，更新数量
        existingCartItem.quantity = device.quantity;
        this.$message.success(`已更新 ${device.device_name} 的数量`);
      } else {
        // 如果配置不存在，创建新的项目
        const cartItem = {
          id: cartItemKey, // 添加唯一标识
          device_id: device.id,
          device_name: device.device_name,
          factory: device.factory,
          is_need: device.is_need,
          quantity: device.quantity,
          accessories: selectedAccessories,
          shipping_info: { // 新增发货信息，自动填充当前合同信息
            recipient_name: this.currentContract?.recipient_name || '',
            recipient_tel: this.currentContract?.recipient_tel || '',
            recipient_address: this.currentContract?.recipient_address || '',
            remark: ''
          }
        };
        
        this.cartItems.push(cartItem);
        this.$message.success(`已添加 ${device.device_name} `);
      }
    },
    
    // 移除项目
    removeFromCart(index) {
      this.cartItems.splice(index, 1);
      this.$message.success('已移除');
    },
    
    // 清空
    clearCart() {
      this.cartItems = [];
      // 重置产品搜索
      this.productSearchKeyword = '';
      this.filteredDeviceList = [...this.deviceList];
      // this.$message.success('购物车已清空');
    },
    
    // 处理配件选择变化
    handleAccessoryChange(device, accessory) {
      if (accessory.selected) {
        // 如果配件有规格，确保选择了规格
        if (accessory.skus && accessory.skus.length > 0 && !accessory.selectedSkuId) {
          this.$set(accessory, 'selectedSkuId', accessory.skus[0].id);
        }
      } else {
        // 如果取消选择配件，清空规格选择
        this.$set(accessory, 'selectedSkuId', null);
      }
    },
    
    // 处理设备数量变化，同步购物车中的数量
    handleDeviceQuantityChange(device) {
      // 收集当前选中的配件
      const selectedAccessories = [];
      device.accessories.forEach(accessory => {
        if (accessory.selected) {
          const accessoryItem = {
            id: accessory.id,
            sku_id: accessory.selectedSkuId || 'no_sku'
          };
          selectedAccessories.push(accessoryItem);
        }
      });
      
      // 生成当前配置的哈希值
      const currentHash = this.generateAccessoriesHash(selectedAccessories);
      
      // 查找购物车中对应配置的商品并更新数量
      const cartItem = this.cartItems.find(item => {
        const itemHash = this.generateAccessoriesHash(item.accessories);
        return item.device_id === device.id && itemHash === currentHash;
      });
      
      if (cartItem) {
        cartItem.quantity = device.quantity;
      }
    },
    
    // 生成配件组合的哈希值，用于区分不同配置
    generateAccessoriesHash(accessories) {
      if (!accessories || accessories.length === 0) {
        return 'no_accessories';
      }
      
      // 按配件ID和SKU ID排序，确保相同配置生成相同的哈希值
      const sortedAccessories = accessories
        .map(acc => ({
          id: acc.id,
          sku_id: acc.sku_id || 'no_sku'
        }))
        .sort((a, b) => {
          if (a.id !== b.id) return a.id - b.id;
          return (a.sku_id || '').localeCompare(b.sku_id || '');
        });
      
      // 生成简单的哈希字符串
      return sortedAccessories
        .map(acc => `${acc.id}:${acc.sku_id}`)
        .join('|');
    },
    
    // 提交订单生成
    async submitOrderGeneration() {
      try {
        // 检查购物车是否为空
        if (this.cartItems.length === 0) {
          this.$message.warning('请至少选择一个产品生成');
          return;
        }
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        this.orderLoading = true;
        
        // 收集购物车中的订单项目
        const orderItems = this.cartItems.map(item => ({
          device_id: item.device_id,
          device_name: item.device_name,
          quantity: item.quantity,
          accessories: item.accessories,
          shipping_info: item.shipping_info // 添加发货信息
        }));
        
        const orderData = {
          contract_id: this.currentContract.id,
          customer_id: this.currentContract.customer_id,
          order_items: orderItems
        };
        
        console.log('生成订单数据:', orderData);
        
        const response = await generateOrder(orderData);
        
        if (response.data && response.data.code === 1) {
          this.$message.success(`成功生成 ${response.data.order_count} 个订单`);
          this.orderDialogVisible = false;
          this.clearCart(); // 清空购物车
          // 可以跳转到订单管理页面
          // this.$router.push('/order-management');
        } else {
          this.$message.error(response.data.msg || '生成订单失败');
        }
      } catch (error) {
        console.error('生成订单失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('生成订单失败');
        }
      } finally {
        this.orderLoading = false;
      }
    },
    
    // 查看订单
    async handleViewOrders(contract) {
      this.currentContractForOrders = contract;
      this.ordersDialogVisible = true;
      this.ordersLoading = true;
      
      try {
        const response = await getOrdersByContractId(contract.id);
        if (response.data && response.data.code === 1) {
          this.ordersList = response.data.data || [];
        } else {
          this.$message.error(response.data.msg || '获取订单列表失败');
          this.ordersList = [];
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        this.$message.error('获取订单列表失败');
        this.ordersList = [];
      } finally {
        this.ordersLoading = false;
      }
    },
    
    // 删除订单
    async handleDeleteOrder(order) {
      try {
        await this.$confirm(`确定要删除该订单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 调用删除订单API
        const response = await deleteOrder(order.id);
        
        if (response.data && response.data.code === 1) {
          this.$message.success('删除订单成功');
          // 重新加载订单列表
          this.handleViewOrders(this.currentContractForOrders);
        } else {
          this.$message.error(response.data.msg || '删除订单失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除订单失败:', error);
          this.$message.error('删除订单失败');
        }
      }
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'warning',   // 生产中
        2: 'success',   // 已发货
        3: 'info'       // 已签收
      };
      return statusMap[status] || 'info';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '生产中',
        2: '已发货',
        3: '已签收'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 格式化日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return '-';
      return new Date(timestamp * 1000).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    
    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00';
      return parseFloat(amount).toFixed(2);
    },

    // 同步发货信息
    syncShippingInfo() {
      this.autoFillShippingInfo();
      this.$message.success('已同步所有产品的发货信息');
    }
  }
}
</script>

<style scoped>
.contract-list-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 4px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}

.pagination-container .el-pagination {
  margin-left: auto;
  margin-right: 0;
}

.el-descriptions {
  margin-top: 20px;
}

.el-descriptions-item__label {
  font-weight: bold;
  background-color: #f5f7fa;
}

.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.image-slot p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
}

/* 产品选择弹窗样式 */
.product-selection-container {
  max-height: 600px;
  overflow-y: auto;
}

.product-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #67c23a;
  padding-bottom: 5px;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
}

.product-item:hover {
  border-color: #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.1);
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.factory-info {
  margin-bottom: 10px;
  color: #606266;
  font-size: 13px;
}

.factory-info span {
  margin-right: 20px;
}

.accessories-list h5 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 10px;
}

/* 查看订单弹窗样式 */
.orders-container {
  max-height: 1000px;
  overflow-y: auto;
}

.orders-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

/* 产品选择弹窗样式 */
.product-selection-container {
  max-height: 600px;
  overflow-y: auto;
}

.contract-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.contract-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.contract-info p {
  margin: 5px 0;
  color: #606266;
}

.product-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 15px;
  padding: 15px;
  background-color: #fff;
}

.product-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.product-header .el-checkbox {
  margin-right: 10px;
}

.factory-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.factory-info span {
  display: block;
  margin-bottom: 5px;
  color: #606266;
  font-size: 13px;
}

.accessories-list {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}

/* 设备选择弹窗样式 */
.device-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 15px;
  padding: 15px;
  background-color: #fff;
}

.device-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.device-header .el-checkbox {
  margin-right: 10px;
}

.device-quantity {
  margin: 10px 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.accessory-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #fafafa;
}

.accessory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.accessory-name {
  font-weight: 500;
  color: #303133;
}

.sku-selection {
  margin: 8px 0;
  padding: 8px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}



.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.form-label {
  width: 80px;
  font-size: 12px;
  color: #606266;
  margin-right: 8px;
}

.sku-selection .form-label {
  width: 100px;
}

.device-quantity .form-label {
  width: 100px;
}

.accessories-list h5 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 10px;
}

.accessory-item {
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  color: #409eff;
  font-size: 13px;
  text-align: center;
}



.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 300px;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
  border-radius: 4px;
}

.image-slot p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

/* 产品选择弹窗样式 */
.product-selection-container {
  max-height: 70vh;
  overflow-y: auto;
}

.contract-info {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.contract-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.contract-info p {
  margin: 5px 0;
  color: #606266;
}

.product-list {
  margin-bottom: 30px;
}

.product-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.device-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.device-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-selector label {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.factory-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 13px;
  color: #606266;
}

.accessories-list h5 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.accessory-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  background-color: #fafafa;
}

.accessory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.accessory-name {
  font-weight: 500;
  color: #303133;
}

.sku-selection {
  margin-top: 8px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-label {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
}

/* 已选产品样式 */
.selected-products {
  border-top: 2px solid #409eff;
  padding-top: 20px;
}

.selected-products h4 {
  margin: 0 0 15px 0;
  color: #303133;
  display: flex;
  align-items: center;
}

.empty-cart {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 2px dashed #dee2e6;
}

.cart-items {
  /* 移除最大高度限制和滚动条 */
  /* max-height: 300px; */
  /* overflow-y: auto; */
}

.cart-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 10px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.cart-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.device-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.device-config {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.cart-item-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quantity-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-section label {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
}

.accessories-section {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.accessories-section label {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
  margin-top: 2px;
}

.accessories-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 发货信息样式 */
.shipping-info-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #dcdfe6;
}

.shipping-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
}

.shipping-title i {
  margin-right: 5px;
  font-size: 16px;
}

.shipping-form {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.shipping-form .form-item {
  margin-bottom: 15px;
}

.shipping-form .form-label {
  display: block;
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap; /* 防止标签文字换行 */
}

.shipping-form .el-input,
.shipping-form .el-textarea {
  width: 100%;
}

.shipping-form .el-input__inner,
.shipping-form .el-textarea__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.shipping-form .el-input__inner:focus,
.shipping-form .el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.shipping-form .el-input:hover .el-input__inner,
.shipping-form .el-textarea:hover .el-textarea__inner {
  border-color: #c0c4cc;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 固定列样式 */
.el-table .el-table__fixed-right {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

.el-table .el-table__fixed-right::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 1px;
  height: 100%;
  background-color: #EBEEF5;
}

/* 确保固定列在滚动时正确显示 */
.el-table__body-wrapper {
  overflow-x: auto;
}

/* 产品搜索样式 */
.product-search {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.product-search .el-input {
  width: 100%;
  max-width: 300px;
}

.product-search .el-input__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.product-search .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.product-search .el-input:hover .el-input__inner {
  border-color: #c0c4cc;
}

/* 已选产品样式 */
</style>